<template>
  <div class="container">
    <div class="vTitle"><span>查看病人</span></div>
    <div class="vForm">
      <div class="item">
        <div class="label">病人姓名：<i class="required">*</i></div>
        <div class="inputBox" v-if="edit">
          <input
            type="text"
            v-model="form.username"
            class="vInput"
            placeholder="输入病人姓名"
          />
        </div>
        <div class="textBox" v-else>{{ form.username }}</div>
      </div>
      <div class="item">
        <div class="label">手机号：<i class="required">*</i></div>
        <div class="inputBox" v-if="edit">
          <input
            type="text"
            v-model="form.mobile"
            class="vInput"
            placeholder="输入联系手机号"
          />
        </div>
        <div class="textBox" v-else>{{ form.mobile }}</div>
      </div>
      <div class="item">
        <div class="label">密码：<i class="required">*</i></div>
        <div class="textBox buttonGroup">
          <div class="smallButton" @click="editPassword">
            <i class="iconfont icon-edit"></i>
            <span>修改</span>
          </div>
        </div>
      </div>
      <div class="item">
        <div class="label">性别：<i class="required">*</i></div>
        <div class="toggleBox">
          <div class="box" @click="toggleSex">
            <div class="slider" :style="{ left: `${form.sex * 66}px` }"></div>
            <div class="front block" :class="form.sex == 0 ? 'active' : ''">
              <i class="iconfont icon-male"></i><span>男</span>
            </div>
            <div class="back block" :class="form.sex == 0 ? '' : 'active'">
              <i class="iconfont icon-female"></i><span>女</span>
            </div>
          </div>
        </div>
      </div>
      <div class="item">
        <div class="label">生日：<i class="required">*</i></div>
        <div class="inputBox" v-if="edit">
          <input
            type="text"
            class="vInput"
            v-model="form.birthday"
            placeholder="可直接输入8位日期，会自动添加连接符，比如20250218"
            @input="autoDate"
            @keydown.delete="handleDelete"
            ref="birthdayInput"
          />
        </div>
        <div class="textBox" v-else>{{ form.birthday }}</div>
      </div>
      <div class="item">
        <div class="label">基础病：</div>
        <div class="inputBox" v-if="edit">
          <input
            type="text"
            class="vInput"
            v-model="form.illness"
            placeholder="若有基础病请填写，可以不填"
          />
        </div>
        <div class="textBox" v-else>{{ form.illness }}</div>
      </div>
      <div class="item">
        <div class="buttonGroup">
          <div class="vButton" @click="toggleEdit" v-if="edit">取消</div>
          <div class="vButton primary" @click="submit" v-if="edit">提交</div>
          <div class="vButton primary" @click="toggleEdit" v-else>编辑</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import { vConfirm } from "@/plugins/vConfirm";
import { vToast } from "@/plugins/vToast";
import router from "@/route/index";
import { useRoute } from "vue-router";
import { userInfo, userEdit, updatePassword } from "@/api";
const edit = ref(false);
const route = useRoute();
console.log("ID参数:", route.query.id);
const birthdayInput = ref(null);
let lastValue = "";
const form = reactive({
  username: "",
  password: "",
  birthday: "",
  sex: 0,
  mobile: "",
  illness: "",
});
const getUserInfo = () => {
  userInfo({ id: route.query.id }).then((res) => {
    if (res.code == 200) {
      Object.assign(form, res.data);
    }
  });
};
const toggleEdit = () => {
  edit.value = !edit.value;
};
onMounted(() => {
  getUserInfo();
});
const toggleSex = () => {
  if (edit.value) {
    form.sex = form.sex == 0 ? 1 : 0;
  }
};
const autoDate = () => {
  const input = birthdayInput.value;
  const cursorPos = input.selectionStart;
  let value = form.birthday.replace(/\D/g, "");
  let formatted = "";

  // 处理年份 (0-4位)
  const year = value.substring(0, 4);
  if (year.length > 0) {
    const yearNum = parseInt(year);
    if (year.length === 4 && (yearNum < 1900 || yearNum > 2025)) {
      formatted = year; // 无效年份保留但不加-
    } else {
      formatted = year;
      // 满4位有效且后面还有数字时加-
      if (year.length === 4 && value.length > 4) formatted += "-";
    }
    value = value.substring(4);
  }

  // 处理月份 (0-2位)
  const month = value.substring(0, 2);
  if (month.length > 0 && formatted.length > 0) {
    const monthNum = parseInt(month);
    if (formatted.endsWith("-")) {
      if (month.length === 2 && (monthNum < 1 || monthNum > 12)) {
        formatted += month; // 无效月份保留但不加-
      } else {
        formatted += month;
        // 满2位有效且后面还有数字时加-
        if (month.length === 2 && value.length > 2) formatted += "-";
      }
      value = value.substring(2);
    }
  }

  // 处理日期 (0-2位)
  const day = value.substring(0, 2);
  if (day.length > 0 && formatted.endsWith("-")) {
    formatted += day; // 日期部分不验证
  }

  // 更新值并调整光标
  lastValue = form.birthday;
  form.birthday = formatted;
  adjustCursorPos(cursorPos, lastValue, formatted);
};

const adjustCursorPos = (oldPos, oldStr, newStr) => {
  nextTick(() => {
    let newPos = oldPos;
    // 处理新增分隔符导致的位置偏移
    if (newStr.length > oldStr.length) {
      const addedDash = newStr.split("-").length - oldStr.split("-").length;
      newPos += addedDash;
    }
    // 限制光标位置不超过字符串长度
    newPos = Math.min(newPos, newStr.length);
    birthdayInput.value.setSelectionRange(newPos, newPos);
  });
};

const handleDelete = (e) => {
  // 捕获删除键事件，手动处理分隔符删除
  const cursorPos = birthdayInput.value.selectionStart;
  if (form.birthday[cursorPos - 1] === "-") {
    form.birthday =
      form.birthday.slice(0, cursorPos - 1) + form.birthday.slice(cursorPos);
    nextTick(() =>
      birthdayInput.value.setSelectionRange(cursorPos - 1, cursorPos - 1)
    );
    e.preventDefault(); // 阻止默认删除行为
  }
};
const validations = reactive({
  username: { valid: true, message: "" },
  mobile: { valid: true, message: "" },
  birthday: { valid: true, message: "" },
});

const validateName = () => {
  validations.username.valid = form.username.trim().length >= 2;
  validations.username.message = validations.username.valid
    ? ""
    : "姓名至少需要2个字符";
};

const validateMobile = () => {
  const reg = /^1[3-9]\d{9}$/;
  validations.mobile.valid = reg.test(form.mobile);
  validations.mobile.message = validations.mobile.valid
    ? ""
    : "请输入有效的手机号码";
};

const validateBirthday = () => {
  const dateReg = /^(19\d{2}|20[0-2]\d)-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
  validations.birthday.valid = dateReg.test(form.birthday);
  validations.birthday.message = validations.birthday.valid
    ? ""
    : "日期格式应为YYYY-MM-DD且有效";
};

const showError = (message) => {
  vToast({
    message: message,
  });
};

const submit = async () => {
  // 自动补全密码
  if (!form.password) form.password = "111111";

  // 执行验证
  validateName();
  validateMobile();
  validateBirthday();

  // 收集错误信息
  const errors = [];
  if (!form.username.trim()) errors.push("病人姓名");
  if (!form.mobile) errors.push("手机号");
  if (!form.birthday) errors.push("生日");
  if (errors.length > 0) {
    return showError(`以下必填项未填写：${errors.join("、")}`);
  }

  // 检查验证状态
  const validationErrors = [
    ...(!validations.username.valid ? [validations.username.message] : []),
    ...(!validations.mobile.valid ? [validations.mobile.message] : []),
    ...(!validations.birthday.valid ? [validations.birthday.message] : []),
  ];

  if (validationErrors.length > 0) {
    return showError(validationErrors.join("\n"));
  }

  let parmas = { id: form.id };
  delete form.password;
  delete form.isadmin;
  delete form.id;
  form.sex = Math.floor(form.sex);
  parmas.data = form;
  // 提交逻辑
  userEdit(parmas)
    .then((res) => {
      if (res.code == 200) {
        vConfirm({
          message: "修改成功，是否返回",
        })
          .then(() => {
            router.push({ name: "index" });
          })
          .catch(() => {});
      }
    })
    .catch((err) => {
      showError(`提交失败：${err.message || "服务器错误"}`);
    });
};

const viewPassword = () => {};
const editPassword = () => {
  vConfirm({
    title: "修改密码",
    message: "请输入新密码",
    showInput: true,
    inputPlaceholder: "大于6位新密码",
  })
    .then((value) => {
      console.log("用户输入:", value);
      updatePassword({ new_password: value, id: form.id }).then((res) => {
        if (res.code == 200) {
          vToast({
            message: "密码修改成功!",
          });
        } else {
          vToast({
            message: "密码修改失败!" + res.msg,
          });
        }
      });
    })
    .catch((e) => {});
};
</script>

<style lang="less" scoped>
.container {
  flex-grow: 1;
  overflow-y: auto;
  .vButton {
    cursor: pointer;
  }
}
.textBox {
  font-size: 18px;
  font-weight: 200;
}
.buttonGroup {
  gap: 14px;
}
.smallButton {
  cursor: pointer;
  font-size: 14px;
  display: flex;
  gap: 4px;
  align-items: center;
  border: var(--bs-border-color) 1px solid;
  padding: 2px;
  width: 66px;
  justify-content: center;
  border-radius: 2px;
  transition: all 0.3s;
  .iconfont {
    font-size: 14px;
  }
  &:hover {
    background: var(--bs-theme-color);
    color: #fff;
  }
}
</style>